package de.trebings.gia.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.*;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.restfb.Connection;

import de.trebings.gia.entities.Password;
import de.trebings.gia.entities.User;

@SuppressWarnings("serial")
public class UserAdminServlet extends AbstractAdminServlet {

	public void processGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, JSONException {
		String responseString = "";

		String action = req.getParameter("action");

		if ("getUsers".equals(action)) {

			String accessToken = req.getParameter("accessToken");
			System.out.println("token: " + accessToken);

			JSONObject json = new JSONObject();

			if (isAuthorized(accessToken)) {
				json.put("isAuthenticated", "X");

				List<User> users = um.getUsers();
				JSONArray userArrayJSON = new JSONArray();
				JSONObject userLineJSON;

				for (User user : users) {
					userLineJSON = new JSONObject();
					userLineJSON.put("name", user.getName());
					userLineJSON.put("email", user.getEmail());
					userLineJSON.put("status", user.getStatus());
					userLineJSON.put("fbId", user.getFbId());
					userArrayJSON.put(userLineJSON);
				}

				json.put("users", userArrayJSON);
			} else {
				json.put("isAuthenticated", " ");
			}
			responseString = json.toString();
			System.out.println(responseString);
			resp.getWriter().write(responseString);

//			getFacebookFriends();
		}
	}

	// used to initially populate the user list with my friends from facebook
	private void getFacebookFriends() {
		Connection<com.restfb.types.User> myFriends = facebookClient
				.fetchConnection("me/friends", com.restfb.types.User.class);
		List<com.restfb.types.User> myFriendsUsers = myFriends.getData();
		int numberOfFriends = myFriendsUsers.size();
		System.out.println("Number of Friends: " + numberOfFriends);
		
		for (com.restfb.types.User friend : myFriendsUsers) {
			System.out.println(friend.getName() + ":" + friend.getId() + ":"
					+ friend.getEmail());

			User user = null;
			user = um.getUserByFbId(friend.getId());
			if (user == null) {
				user = new User();
				user.setFbId(friend.getId());
				user.setName(friend.getName());
				user.setStatus(User.AUTHORIZED);
				pm.makePersistent(user);
			}
		}
	}

	public void processPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, JSONException {
		String responseString = "";

		String action = req.getParameter("action");

		if ("newPassword".equals(action)) {
			String accessToken = req.getParameter("accessToken");

			if (isAuthorized(accessToken)) {
				String passwordString = req.getParameter("password");
				
				// delete old passwords
				String query = "select from " + Password.class.getName();
				List<Password> existingPasswords = (List<Password>) pm.newQuery(query).execute();
				for(Password password : existingPasswords){
					pm.deletePersistent(password);
				}
				
				// set new password
				Password password = new Password(passwordString);
				pm.makePersistent(password);
			}
		}
		
		if ("authorize".equals(action)) {
			String accessToken = req.getParameter("accessToken");

			if (isAuthorized(accessToken)) {
				String email = req.getParameter("email");
				String fbId = req.getParameter("fbId");
				System.out.println("authorize email: " + email + " fbId: "
						+ fbId);
				User user;
				if ("".equals(email)) {
					user = um.getUserByFbId(fbId);
				} else {
					user = um.getUserByEmail(email);
				}
				if (user != null) {
					user.setStatus(User.AUTHORIZED);
				}
			} else {
				// TODO error handling
			}
		}

		if ("delete".equals(action)) {
			String accessToken = req.getParameter("accessToken");

			if (isAuthorized(accessToken)) {
				String email = req.getParameter("email");
				String fbId = req.getParameter("fbId");
				System.out.println("delete email: " + email + " fbId: " + fbId);
				User user;
				if ("".equals(email)) {
					user = um.getUserByFbId(fbId);
				} else {
					user = um.getUserByEmail(email);
				}
				if (user != null) {
					pm.deletePersistent(user);
					System.out.println("deletion done successfully");
				}
			} else {
				// TODO error handling
			}
		}

		if ("addUser".equals(action)) {
			String accessToken = req.getParameter("accessToken");

			if (isAuthorized(accessToken)) {
				String email = req.getParameter("email");
				System.out.println("create email: " + email);
				if (!"".equals(email)) {
					User user = new User();
					user.setEmail(email);
					user.setStatus(User.AUTHORIZED);
					pm.makePersistent(user);
				}
			} else {
				// TODO error handling
			}
		}

		resp.getWriter().write(responseString);
	}
}
